package practice;

/**
 * @Description: https://leetcode.cn/problems/trapping-rain-water/
 * @Author Ammar
 * @Create 2023/7/22 22:04
 */
public class _42_接雨水 {
    public int trap(int[] height) {
        if (height.length <= 2) return 0;
        int r = height.length - 1;
        int l = 0;
        int leftMax = height[0];
        int rightMax = height[height.length - 1];
        int min = Math.min(leftMax, rightMax);
        int water = 0;
        while (l <= r) {
            int heightL = height[l];
            int heightR = height[r];
            if (heightL <= heightR) {
                if (heightL < min) {
                    water += min - heightL;
                } else {
                    leftMax = heightL;
                    min = leftMax;
                }
                l++;
            } else {
                if (heightR < min) {
                    water += min - heightR;
                } else {
                    rightMax = heightR;
                    min = rightMax;
                }
                r--;
            }
        }
        return water;
    }
}
